package com.lean.android.ad.repository.localcache

import android.os.SystemClock
import androidx.annotation.Keep
import com.lean.android.ad.core.AdSdk
import com.lean.android.cache.CacheFactory
import com.lean.android.cache.boolCache
import com.lean.android.cache.intCache
import com.lean.android.cache.longCache
import com.lean.android.cache.observableBoolCache
import com.lean.android.cache.stringCache
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.util.UUID
import kotlin.math.abs

@Keep
object AdLocalCache {

    private val cache by lazy {
        CacheFactory.localCache
    }

    var oaid by stringCache { cache }
        internal set

    var deviceId by stringCache { cache }
        internal set


    //隐私协议是否同意
    var isPrivacyAgree by observableBoolCache(false, { newValue ->
        updatePrivacyValue(newValue)
    }, {
        cache
    })


    private val _privacyAgreeFlow = MutableStateFlow(isPrivacyAgree)

    private fun updatePrivacyValue(newValue: Boolean) {
        _privacyAgreeFlow.value = newValue
    }

    internal val privacyAgreeFlow = _privacyAgreeFlow.asStateFlow()

    var splashAdShowTime by longCache {
        cache
    }

    fun canShowSplashAd(): Boolean {
        val timeDiffInMills = System.currentTimeMillis() - splashAdShowTime
        return timeDiffInMills >= AdSdk.getAdConfig().adParamsProvider.getReSplashTimeLimit()
    }

    var deviceStartTime by longCache { cache }
        internal set


    private fun ensureDeviceStartTime() {
        val currentTime = System.currentTimeMillis() - SystemClock.elapsedRealtimeNanos() / 1000000
        if (abs(currentTime - deviceStartTime) > 5000L) {
            deviceStartTime = currentTime
        }
    }

    private fun ensureDeviceId() {
        if (deviceId.isEmpty()) {
            deviceId = UUID.randomUUID().toString()
        }
    }

    var vipDialogShowed by boolCache { cache }
        internal set


    fun init() {
        ensureDeviceStartTime()
        ensureDeviceId()
    }

}